package com.mrzhou.web.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.HttpServletBean;

import javax.servlet.ServletException;

/**
 * 在springboot应用启动时就初始化DispatcherServlet, 防止第一次请求时接口相应缓慢
 * @author qiang.zhou
 */
@Slf4j
public class InitDispatcherServlet implements BeanDefinitionRegistryPostProcessor {

    private BeanDefinitionRegistry beanDefinitionRegistry;

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
        this.beanDefinitionRegistry = beanDefinitionRegistry;
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        try {
            log.info("项目启动时初始化DispatchServlet.....");
            HttpServletBean httpServletBean = configurableListableBeanFactory.getBean(DispatcherServlet.class);
            httpServletBean.init();
        }   catch (ServletException e) {
            log.warn("初始化DispatchServlet失败: {}", e);
        } catch (BeansException e) {
            log.warn("未能初始化dispatcherServletRegistration，因为没有找到这个bean！");
        }
    }

}
